import logging


import re
from django import http
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.urls import reverse

from apps.users.models import User


from django.shortcuts import render, redirect
from django.views import View


class RegisterView(View):
    def get(self,request):
        return render(request, 'register.html')
    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        # 校验参数是否齐全
        if not all([username,password,password2,mobile]):
            return http.HttpResponseBadRequest('参数不全')
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
            return http.HttpResponseBadRequest('请输入5-20个字符的用户名')
        if not re.match(r'^[0-9a-z-A-Z]{8,20}',password):
            return http.HttpResponseBadRequest('请输入8-20位的密码')
        if password != password2:
            return http.HttpResponseBadRequest('两次密码输入不一致')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('请输入正确的手机号')

        #数据入库
        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                mobile=mobile
            )
        except Exception as e:
            logge = logging.getLogger('django')
            logge.error(e)

        login(request, user)

        return redirect(reverse('content:index'))

class UsernameCountView(View):
    def get(self, request,username):
        count = User.objects.filter(username=username).count()

        return http.JsonResponse({'code':0,'count':count})

class MobileCountView(View):
    def get(self,request ,mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code':0,'count': count})


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')
    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('pwd')
        remembered = request.POST.get('remembered')

        if not all([username, password]):
            return http.HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$',username):
            return http.HttpResponseBadRequest('请输入正确的用户名或者手机号')
        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return http.HttpResponseBadRequest('密码最少8位，最长20位')
        user = authenticate(username=username,password=password)
        if user is None:
            return http.HttpResponseBadRequest('账号或密码错误')

        login(request, user)
        if remembered == 'on':
            #有效期默认为两周
            request.session.set_expiry(None)
        else:
            #否则六级、浏览结束关闭会话
            request.session.set_expiry(0)
        response = redirect(reverse('content:index'))
        #登陆时用户名写到cookie
        response.set_cookie('username', user.username, max_age=3600)
        return response

class LogoutView(View):
    def get(self,request):
        request.session.flush()
        logout(request)
        #退出之后返回首页
        response = redirect(reverse('content:index'))
        response.delete_cookie('username')
        return response

class UserCenterView(LoginRequiredMixin,View):
    def get(self,request):
        context = {
            'username':request.user.username,
            'mobile':request.user.mobile,
            'email':request.user.email,
            'email_active':request.user.email_active
        }
        return render(request, 'user_center_info.html',context=context)

class AddressView(LoginRequiredMixin, View):
    def get(self,request):
        return render(request, 'user_center_site.html')